# Celery配置
import os

from celery import Celery
from datetime import timedelta
from dotenv import load_dotenv

load_dotenv()
broker = os.getenv("BROKER_URL")
backend = os.getenv("RESULT_BACKEND")
print(broker, backend)


class CeleryConfig:
    broker_url = broker
    result_backend = backend
    task_serializer = "json"
    accept_content = ["json"]
    result_serializer = "json"
    timezone = "Asia/Shanghai"
    enable_utc = False


# 创建celery实例
celery_app = Celery(
    "worker",
    broker=CeleryConfig.broker_url,
    backend=CeleryConfig.result_backend,
)

# 基础配置
celery_app.conf.update(
    task_serializer=CeleryConfig.task_serializer,
    result_serializer=CeleryConfig.result_serializer,
    accept_content=CeleryConfig.accept_content,
    timezone=CeleryConfig.timezone,
    enable_utc=CeleryConfig.enable_utc,
)
# 自动发现任务
celery_app.autodiscover_tasks([
    'celery_related.common_tasks',
    'celery_related.delay_tasks',
    'celery_related.sche_tasks',
], force=True)
# 定时任务(如需)
celery_app.conf.beat_schedule = {
    "crawl_info": {
        "task": "celery_related.sche_tasks.tasks.crwal_info",
        "schedule": timedelta(seconds=5),
        "args": (),
    }
}

if __name__ == '__main__':
    celery_app.start(["worker", '--beat', '--loglevel=info'])

# 或者通过命令启动：celery -A celery_related.celery_app:celery_app worker --beat --loglevel=info
